#include <gtk/gtk.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "gui_callback.h"
#include "server_connect.h"

GtkBuilder *builder;
int socketfd_login;
int socketfd_userinfo;
int socketfd_traininfo;
int socketfd_orderinfo;

//连接服务器
bool connect_server() {
	int len;
	int result;

	struct sockaddr_in address_login;
	socketfd_login = socket(AF_INET, SOCK_STREAM, 0);
	address_login.sin_family = AF_INET;
	address_login.sin_addr.s_addr = inet_addr(HOSTNAME);
	address_login.sin_port = htons(PORT_LOGIN);
	len = sizeof(address_login);

	result = connect(socketfd_login, (struct sockaddr*) &address_login, len);
	if (result != 0) {
		return false;
	}

	struct sockaddr_in address_userinfo;
	socketfd_userinfo = socket(AF_INET, SOCK_STREAM, 0);
	address_userinfo.sin_family = AF_INET;
	address_userinfo.sin_addr.s_addr = inet_addr(HOSTNAME);
	address_userinfo.sin_port = htons(PORT_USERINFO);
	len = sizeof(address_userinfo);

	result = connect(socketfd_userinfo, (struct sockaddr*) &address_userinfo,
			len);
	if (result != 0) {
		return false;
	}

	struct sockaddr_in address_traininfo;
	socketfd_traininfo = socket(AF_INET, SOCK_STREAM, 0);
	address_traininfo.sin_family = AF_INET;
	address_traininfo.sin_addr.s_addr = inet_addr(HOSTNAME);
	address_traininfo.sin_port = htons(PORT_TRAININFO);
	len = sizeof(address_traininfo);

	result = connect(socketfd_traininfo, (struct sockaddr*) &address_traininfo,
			len);
	if (result != 0) {
		return false;
	}

	struct sockaddr_in address_orderinfo;
	socketfd_orderinfo = socket(AF_INET, SOCK_STREAM, 0);
	address_orderinfo.sin_family = AF_INET;
	address_orderinfo.sin_addr.s_addr = inet_addr(HOSTNAME);
	address_orderinfo.sin_port = htons(PORT_ORDERINFO);
	len = sizeof(address_orderinfo);

	result = connect(socketfd_orderinfo, (struct sockaddr*) &address_orderinfo,
			len);
	if (result != 0) {
		return false;
	}

	return true;
}

int main(int argc, char *argv[]) {
	GtkWidget *global_window;

	gtk_init(&argc, &argv);

	builder = gtk_builder_new();
	gtk_builder_add_from_file(builder, "gui.glade", NULL );
	global_window =
			GTK_WIDGET(gtk_builder_get_object(builder, "global_window"));
	gtk_builder_connect_signals(builder, NULL );

	gtk_widget_show(global_window);

	if (!connect_server()) {
		gtk_show_error(GTK_WINDOW(global_window), "%s",
				"您当前的网络不稳定，无法连接到服务器\n请确保服务器已经开启并保证网络连接正确", "网络连接错误");
		return -1;
	}
	gtk_main();

	return 0;
}
